package cn.itsource.basic.base.controller;

import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
public class UploadController {
    //上传文件  MultipartFile 用于接收前端传递的上传文件，图片等数据。
    @PostMapping
    public AjaxResult uploadFile(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            //得到上传时的文件名
            String filename = file.getOriginalFilename();
            //lastIndexOf找到最后一个点的位置 ，后面+1是需要点后面一位的索引
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastdfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器忙!请稍后重试");
        }
    }

    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam(value = "path", required = true) String path){
        String pathTmp = path.substring(1);
        String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));
        String remotePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
        boolean flag = FastdfsUtil.delete(groupName, remotePath);
        if (flag){
            return AjaxResult.me();
        }else {
            return AjaxResult.me().setSuccess(false).setMessage("服务器忙!请稍后重试");
        }
    }
}
